package bg.btanev.eightyfour.gwtfacade.commandhandler;

import org.apache.commons.lang.Validate;

import bg.btanev.eightyfour.domain.person.Address;
import bg.btanev.eightyfour.domain.person.ContactInfo;
import bg.btanev.eightyfour.domain.person.Person;
import bg.btanev.eightyfour.domain.person.PersonName;
import bg.btanev.eightyfour.gwtfacade.converter.DtoConverter;
import bg.btanev.eightyfour.service.PersonService;
import bg.btanev.eightyfour.shared.command.CommandResult;
import bg.btanev.eightyfour.shared.command.person.UpdatePersonCommand;
import bg.btanev.eightyfour.shared.command.person.UpdatePersonInput;
import bg.btanev.eightyfour.shared.dto.person.AddressDto;
import bg.btanev.eightyfour.shared.dto.person.ContactInfoDto;
import bg.btanev.eightyfour.shared.dto.person.PersonDto;
import bg.btanev.eightyfour.shared.dto.person.PersonNameDto;

/**
 *
 * @author B.Tanev
 *
 */
public class UpdatePersonCommandHandler
		extends
		GenericCommandHandler<UpdatePersonInput, PersonDto, CommandResult<UpdatePersonInput, PersonDto>, UpdatePersonCommand> {

	private final PersonService personService;
	private final DtoConverter converter;

	public UpdatePersonCommandHandler(PersonService personService, DtoConverter converter) {
		super();

		Validate.notNull(personService);
		Validate.notNull(converter);

		this.personService = personService;
		this.converter = converter;
	}

	@Override
	protected PersonDto doExecuteInternal(UpdatePersonInput attachedInput) {
		Validate.notNull(attachedInput);

		PersonDto personInput = attachedInput.getPerson();
		PersonNameDto personNameInput = personInput.getPersonName();
		ContactInfoDto contactInfoInput = personInput.getContactInfo();
		AddressDto addressInput = contactInfoInput.getAddress();

		PersonName personName = new PersonName(personNameInput.getFirstName(), personNameInput.getSurName(),
				personNameInput.getLastName());

		Address address = new Address(addressInput.getCountry(), addressInput.getCity(), addressInput.getStreet());
		ContactInfo contactInfo = new ContactInfo(contactInfoInput.getEmail(), contactInfoInput.getTelephone(),
				address, contactInfoInput.getWebSite());

		PersonDto result = null;
		Person person = personService.updatePersonDetails(personInput.getId(), personName, contactInfo);
		if (person != null) {
			result = converter.domainToDto(person, 2);
		}
		return result;
	}

	@Override
	protected CommandResult<UpdatePersonInput, PersonDto> packCommandResult(UpdatePersonInput input,
			PersonDto detachedResult) {

		return new CommandResult<UpdatePersonInput, PersonDto>(input, detachedResult);
	}

	@Override
	public UpdatePersonInput attach(UpdatePersonInput input) {
		return input;
	}

	@Override
	public PersonDto detach(PersonDto result) {
		return result;
	}
}
